package cn.lwj.webService.util;

import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConverter implements Converter {
	
	public boolean canConvert(Class clazz) {
		return Date.class.isAssignableFrom(clazz);
	}

	public void marshal(Object value, HierarchicalStreamWriter writer,MarshallingContext context) {
		if(value!=null){
			Date date = (Date)value;
			writer.setValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(date));
		}
	}

	public Object unmarshal(HierarchicalStreamReader reader,UnmarshallingContext context) {
		Date date = null;
		try {
			if(reader.getAttribute("xsi:nil")!=null&&reader.getAttribute("xsi:nil").toString().equals("true")&&(reader.getValue()==null||reader.getValue().trim().equals(""))){
				return null;
			}
			else if(reader.getValue()!=null&&!reader.getValue().trim().equals("")&&reader.getValue().length()>10){
				date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(reader.getValue());
			}
			else if(reader.getValue()!=null&&!reader.getValue().trim().equals("")&&reader.getValue().length()==10){
				date = new SimpleDateFormat("yyyy-MM-dd").parse(reader.getValue());
			}
		} catch (ParseException e) {
			throw new ConversionException(e.getMessage(), e);
		}
		return date;
	}

}
